import { formatSuccessResponse } from '../utils/errors.js';
import { authenticate, requirePermission } from '../middleware/auth.js';
import { validateRequest, updateUserSchema } from '../utils/validation.js';
import { getDatabaseSize, optimizeDatabase } from '../utils/prisma.js';

export default async function adminRoutes(fastify, options) {
  
  // 所有管理员路由都需要admin权限
  fastify.addHook('onRequest', authenticate);
  fastify.addHook('onRequest', requirePermission('admin'));
  
  /**
   * 获取所有用户列表
   */
  fastify.get('/users', async (request, reply) => {
    const { role, isActive, search, limit = 50, offset = 0 } = request.query;
    
    const where = {};
    
    if (role) where.role = role;
    if (isActive !== undefined) where.isActive = isActive === 'true';
    if (search) {
      where.OR = [
        { username: { contains: search } },
        { email: { contains: search } },
      ];
    }
    
    const [users, total] = await Promise.all([
      fastify.prisma.user.findMany({
        where,
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          is2faEnabled: true,
          createdAt: true,
          lastLogin: true,
          loginAttempts: true,
          lockedUntil: true,
          notes: true,
          _count: {
            select: { tokens: true },
          },
        },
        take: parseInt(limit),
        skip: parseInt(offset),
        orderBy: { createdAt: 'desc' },
      }),
      fastify.prisma.user.count({ where }),
    ]);
    
    return formatSuccessResponse({
      users,
      total,
      limit: parseInt(limit),
      offset: parseInt(offset),
    });
  });
  
  /**
   * 获取用户详情
   */
  fastify.get('/users/:id', async (request, reply) => {
    const user = await fastify.prisma.user.findUnique({
      where: { id: request.params.id },
      include: {
        _count: {
          select: {
            tokens: true,
            sessions: true,
            auditLogs: true,
          },
        },
      },
    });
    
    if (!user) {
      throw new Error('用户不存在');
    }
    
    // 不返回密码哈希
    delete user.passwordHash;
    delete user.masterKeySalt;
    
    return formatSuccessResponse(user);
  });
  
  /**
   * 更新用户信息
   */
  fastify.put('/users/:id', async (request, reply) => {
    const data = validateRequest(updateUserSchema, request.body);
    
    const user = await fastify.prisma.user.update({
      where: { id: request.params.id },
      data,
      select: {
        id: true,
        username: true,
        email: true,
        role: true,
        isActive: true,
        notes: true,
      },
    });
    
    return formatSuccessResponse(user, '用户信息更新成功');
  });
  
  /**
   * 禁用用户
   */
  fastify.patch('/users/:id/disable', async (request, reply) => {
    await fastify.prisma.user.update({
      where: { id: request.params.id },
      data: { isActive: false },
    });
    
    // 删除所有会话
    await fastify.prisma.userSession.deleteMany({
      where: { userId: request.params.id },
    });
    
    return formatSuccessResponse(null, '用户已禁用');
  });
  
  /**
   * 启用用户
   */
  fastify.patch('/users/:id/enable', async (request, reply) => {
    await fastify.prisma.user.update({
      where: { id: request.params.id },
      data: { isActive: true },
    });
    
    return formatSuccessResponse(null, '用户已启用');
  });
  
  /**
   * 解锁用户
   */
  fastify.patch('/users/:id/unlock', async (request, reply) => {
    await fastify.prisma.user.update({
      where: { id: request.params.id },
      data: {
        loginAttempts: 0,
        lockedUntil: null,
      },
    });
    
    return formatSuccessResponse(null, '用户已解锁');
  });
  
  /**
   * 删除用户
   */
  fastify.delete('/users/:id', async (request, reply) => {
    // 检查是否是最后一个管理员
    const user = await fastify.prisma.user.findUnique({
      where: { id: request.params.id },
    });
    
    if (user.role === 'admin') {
      const adminCount = await fastify.prisma.user.count({
        where: { role: 'admin' },
      });
      
      if (adminCount <= 1) {
        throw new Error('不能删除最后一个管理员账户');
      }
    }
    
    await fastify.prisma.user.delete({
      where: { id: request.params.id },
    });
    
    return formatSuccessResponse(null, '用户已删除');
  });
  
  /**
   * 更新用户备注
   */
  fastify.put('/users/:id/notes', async (request, reply) => {
    const { notes } = request.body;
    
    await fastify.prisma.user.update({
      where: { id: request.params.id },
      data: { notes },
    });
    
    return formatSuccessResponse(null, '备注更新成功');
  });
  
  /**
   * 获取系统统计数据
   */
  fastify.get('/stats', async (request, reply) => {
    const [
      totalUsers,
      activeUsers,
      adminUsers,
      totalTokens,
      totalSessions,
      todayLogins,
    ] = await Promise.all([
      fastify.prisma.user.count(),
      fastify.prisma.user.count({ where: { isActive: true } }),
      fastify.prisma.user.count({ where: { role: 'admin' } }),
      fastify.prisma.token.count(),
      fastify.prisma.userSession.count({
        where: {
          isActive: true,
          expiresAt: { gte: new Date() },
        },
      }),
      fastify.prisma.auditLog.count({
        where: {
          action: 'LOGIN_SUCCESS',
          createdAt: { gte: new Date(new Date().setHours(0, 0, 0, 0)) },
        },
      }),
    ]);
    
    return formatSuccessResponse({
      users: {
        total: totalUsers,
        active: activeUsers,
        admins: adminUsers,
      },
      tokens: {
        total: totalTokens,
      },
      sessions: {
        active: totalSessions,
      },
      activity: {
        todayLogins,
      },
    });
  });
  
  /**
   * 获取审计日志
   */
  fastify.get('/logs', async (request, reply) => {
    const { action, userId, limit = 100, offset = 0 } = request.query;
    
    const where = {};
    if (action) where.action = action;
    if (userId) where.userId = userId;
    
    const [logs, total] = await Promise.all([
      fastify.prisma.auditLog.findMany({
        where,
        include: {
          user: {
            select: {
              username: true,
              email: true,
            },
          },
        },
        take: parseInt(limit),
        skip: parseInt(offset),
        orderBy: { createdAt: 'desc' },
      }),
      fastify.prisma.auditLog.count({ where }),
    ]);
    
    return formatSuccessResponse({
      logs,
      total,
      limit: parseInt(limit),
      offset: parseInt(offset),
    });
  });
  
  /**
   * 优化数据库
   */
  fastify.post('/maintenance/optimize-db', async (request, reply) => {
    const result = await optimizeDatabase();
    return formatSuccessResponse(result, '数据库优化完成');
  });
  
  /**
   * 获取数据库大小
   */
  fastify.get('/maintenance/db-size', async (request, reply) => {
    const size = await getDatabaseSize();
    return formatSuccessResponse(size);
  });
  
  /**
   * 系统健康检查
   */
  fastify.get('/health', async (request, reply) => {
    const dbSize = await getDatabaseSize();
    
    return formatSuccessResponse({
      status: 'healthy',
      database: {
        size: dbSize,
        connected: true,
      },
      uptime: process.uptime(),
      memory: process.memoryUsage(),
    });
  });
}


